package com.atguigu.system.config;

import com.atguigu.system.filter.TokenAuthenticationFilter;
import com.atguigu.system.filter.TokenLoginFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

@Configuration
@EnableWebSecurity //@EnableWebSecurity是开启SpringSecurity的默认行为
@EnableGlobalMethodSecurity(prePostEnabled = true) //开启细粒度方法级别权限控制。
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    RedisTemplate redisTemplate;

    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //提供了默认的登录页。
        //super.configure(http); //集成框架默认的授权。针对所有资源进行控制，必须登录后才能访问。
        //http://ip:port/contextPath/resource
        http.csrf().disable()//禁用CSRF    防止跨站请求伪造
                .cors()// 开启跨域
                .and()
                .authorizeRequests()
                .antMatchers("/admin/system/index/login").permitAll() //放行登录请求，不予拦截
                .anyRequest().authenticated() //其他请求必须登录才能访问。
                .and()
                .addFilterBefore(new TokenAuthenticationFilter(redisTemplate),TokenLoginFilter.class)
                .addFilter(new TokenLoginFilter(super.authenticationManager(),redisTemplate));

        //禁用session.  登录成功用户信息存储在redis缓存中。不需要session对象了。
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    //授权
    @Override
    public void configure(WebSecurity web) throws Exception {
        //这些静态资源不予拦截，忽略，放行。
        web.ignoring().antMatchers("/favicon.ico",
                "/swagger-resources/**", "/webjars/**", "/v2/**", "/doc.html");
    }
}
